package org.example.movies.controller;

import com.alibaba.fastjson.JSONObject;
import org.example.movies.pojo.TUser;
import org.example.movies.service.IUserService;
import org.example.movies.service.impl.UserServiceImpl;
import org.example.movies.utils.ResponseEntity;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RegisterController")
public class RegisterController extends HttpServlet {
    private IUserService service = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        ResponseEntity resp = new ResponseEntity();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        String serverCode = (String) request.getSession().getAttribute("register");
        if (serverCode.equals(code)) {
            boolean flag = service.checkName(username);
            if (flag) {
                resp.setStatus(202);
                resp.setMsg("用户名已存在!");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().println(JSONObject.toJSONString(resp));
            } else {
                int i = service.insertUser(new TUser(email,username,password));
                if (i > 0) {
                    resp.setStatus(100);
                    resp.setMsg("注册成功");
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().println(JSONObject.toJSONString(resp));
                }
            }
        } else {
            resp.setStatus(201);
            resp.setMsg("验证码错误");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(JSONObject.toJSONString(resp));
        }
    }
}
